<template>
  <div class="blog-container">
    <SearchBar></SearchBar>
    <div class="background-card">
      <img src="../../assets/background.jpg" alt="" />
      <div class="avatar">
        <el-avatar
          :src="avatar == '默认头像' ? avatar_url : this.api_url + avatar"
          :size="150"
        ></el-avatar>
      </div>
      <div class="text-container">
        <p>{{ nickname }}</p>
      </div>
    </div>

    <div class="main-blog">
      <el-tabs v-model="activeName" @tab-click="handleClick" type="border-card">
        <el-tab-pane name="first">
          <span slot="label"><i class="el-icon-s-home"></i> 个人资料</span>
          <div class="mainpage">
            <div class="change_avator">
              <p>上传头像:</p>
              <!-- 上传头像的组件 -- -->
              <!-- http://localhost:8888/file/upload -->
              <el-upload
                drag
                class="avatar-uploader"
                action
                :limit="1"
                :http-request="handleUploadForm"
                :before-upload="beforeUploadForm"
                :show-file-list="true"
                :on-preview="handlePreview"
                :file-list="fileList"
                list-type="picture"
                :on-success="handleAvatarSuccess"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>

                <!-- <img v-if="imageUrl" :src="imageUrl" class="show_avatar" /> -->
                <i class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </div>
            <!-- 个人资料表单 -->
            <el-form ref="form" :model="form" label-width="100px">
              <el-form-item label="用户名：">
                <el-input v-model="form.username"></el-input>
              </el-form-item>
              <el-form-item label="密 码：">
                <el-input v-model="form.password" type="password"></el-input>
              </el-form-item>
              <el-form-item label="确 认 密 码：">
                <el-input v-model="ckpassword" type="password"></el-input>
              </el-form-item>
              <el-form-item label="昵 称：">
                <el-input v-model="form.nickname"></el-input>
              </el-form-item>
              <el-form-item label="手机号：">
                <el-input v-model="form.phone" readonly></el-input>
              </el-form-item>
              <el-form-item label="地 址：">
                <el-input v-model="form.address"></el-input>
              </el-form-item>
              <el-form-item label="自我介绍：">
                <el-input v-model="form.description" type="textarea"></el-input>
              </el-form-item>

              <el-form-item>
                <el-button type="primary" @click="onSubmit"
                  >立 即 修 改</el-button
                >
              </el-form-item>
            </el-form>
          </div></el-tab-pane
        >
        <el-tab-pane name="second">
          <span slot="label"><i class="el-icon-user-solid"></i> 我的关注</span>
          <div class="mainpage">
            <div class="follower_container">
              <el-card class="follower_container" shadow="hover">
                鼠标悬浮时显示
              </el-card>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane name="third">
          <span slot="label"><i class="el-icon-user-solid"></i> 关注我的</span>
          <div class="mainpage">
            <el-card class="follower_container" shadow="hover">
              鼠标悬浮时显示
            </el-card>
          </div>
        </el-tab-pane>
        <el-tab-pane name="fourth">
          <span slot="label"><i class="el-icon-tickets"></i> 我的帖子</span>
          <div class="mainpage">
            <el-card class="follower_container" shadow="hover">
              鼠标悬浮时显示
            </el-card>
          </div></el-tab-pane
        >
        <el-tab-pane name="fifth">
          <span slot="label"><i class="el-icon-star-on"></i> 我的收藏</span>
          <div class="mainpage">
            <el-card class="follower_container" shadow="hover">
              鼠标悬浮时显示
            </el-card>
          </div></el-tab-pane
        >
      </el-tabs>
    </div>
  </div>
</template>

<script>
import { mapMutations, mapState } from "vuex";
import SearchBar from "@/components/querypage/SearchBar.vue";

export default {
  name: "PersonView",
  created() {
    // 回到顶部
    document.documentElement.scrollTop = document.body.scrollTop = 0;
    this.getUserInfo();
  },

  computed: {
    ...mapState([
      "avatar_url",
      "phone",
      "avatar",
      "nickname",
      "api_url",
      "token",
    ]),
  },

  data() {
    return {
      //标签页默认开启标识
      activeName: "first",
      user_id: "1",
      fileList: [],
      //用户个人信息修改表单
      form: {
        username: null,
        password: null,
        avatar: null,
        nickname: null,
        phone: null,
        address: null,
        description: null,
      },
      // 确认密码
      ckpassword: null,

      //关注列表
      follow_list: [],
      //粉丝列表
      fans_list: [],
      //帖子列表
      my_post_list: [],
      //收藏列表
      star_post_list: [],
      star_group_list: [],

      // 背景图片
      image: "../../assets/background.jpg",

      //用户当前上传的图片
      imageUrl: "",
    };
  },

  methods: {
    ...mapMutations(["updateUserData"]),

    handleClick(tab, event) {
      console.log(tab, event);
    },

    // 开始上传前验证
    beforeUploadForm(file) {
      // 验证文件大小
      if (file.size / 1024 / 1024 > this.formMaxSize) {
        this.$message({
          message: `上传文件大小不能超过${this.formMaxSize}M!`,
          type: "warning",
        });
        return false;
      }
      // 中文乱码处理
      if (file.raw) {
        let reader = new FileReader(); // 读取文件内容
        reader.readAsText(file.raw, "gb2312"); // 防止中文乱码问题，不加reader.onload方法都不会触发
        reader.onload = function (e) {
          this.contentHtml = e.target.result; // txt文本内容，接下来就可以对其进行校验处理了
        };
      }
      // 验证文件类型
      var testmsg = file.name.substring(file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "png" || testmsg === "jpg";
      if (!extension) {
        this.$message({
          message: "上传文件只能是png,jpg格式!",
          type: "warning",
        });
      }
      return extension;
    },

    //  开始上传
    handleUploadForm(param) {
      let formData = new FormData();
      console.log("==============phone:");
      console.log(this.phone);
      formData.append("phone", this.phone);
      formData.append("file", param.file);
      let loading = this.$loading({
        lock: true,
        text: "上传中，请稍候...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.axios.post("/file/upload", formData).then(({ data }) => {
        console.log(data);
        console.log(data.status)
        if (data.status === 20000) {
          this.$message("上传文件成功，" + data.message);
          this.formFileList = [];
          this.uploadFormFileList = [];
        } else {
          this.formFileList = [];
          this.uploadFormFileList = [];
          this.$message("上传文件失败，" + data.message);
        }
        loading.close();
      });
    },

    handlePreview() {},

    //处理用户修改信息提交
    onSubmit() {
      let form_data = {
        username: this.form.username,
        password: this.form.password,
        avatar: this.form.avatar,
        nickname: this.form.nickname,
        phone: this.form.phone,
        address: this.form.address,
        description: this.form.description,
      };
      if (this.ckpassword == this.form.password) {
        this.axios
          .post("/user/update-user", `${JSON.stringify(form_data)}`, {
            headers: {
              // 设置请求头
              "Content-Type": "application/json",
              Authorization: `${this.token}`,
            },
          })
          .then((res) => {
            if (res.data.status == 20000) {
              this.updateUserData({
                avatar: res.data.data.avatar,
                nickname: res.data.data.nickname,
              });
              this.$message({
                message: "修改成功！",
                type: "success",
                duration: 1250,
                offset: 85,
              });
              this.$router.go(0);
            } else {
              this.$message({
                message: "网络问题,修改失败",
                type: "error",
                duration: 1250,
                offset: 85,
              });
            }
          })
          .catch((err) => {
            console.log(err);
          });
      } else {
        this.$message({
          message: "两次密码不一致！",
          type: "error",
          duration: 1250,
          offset: 85,
        });
      }
    },

    //获取用户上传头像
    handleAvatarSuccess(res, file) {
      console.log(this.res);
      this.imageUrl = URL.createObjectURL(file.raw);
      console.log(this.imageUrl);
    },

    upload_filetype_error() {
      this.$notify.info({
        title: "消息",
        message: "上传头像图片只能是 JPG 格式!",
      });
    },

    upload_filelimit_error() {
      this.$notify.info({
        title: "消息",
        message: "上传头像图片大小不能超过 2MB!",
      });
    },

    //验证头像大小
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (isJPG && !isLt2M) {
        this.$notify.info({
          title: "消息",
          message:
            "上传头像图片大小不能超过 2MB!，上传头像图片只能是 JPG 格式!",
        });
      } else if (!isJPG) {
        this.upload_filetype_error();
      } else if (!isLt2M) {
        this.upload_filelimit_error();
      }
      return isJPG && isLt2M;
    },

    // 获取用户信息
    getUserInfo() {
      let phone = { phone: this.phone };
      this.axios
        .post("/user/get-user-info", `${JSON.stringify(phone)}`, {
          headers: {
            // 设置请求头
            "Content-Type": "application/json",
            Authorization: `${this.token}`,
          },
        })
        .then((res) => {
          if (res.data.status == 20000) {
            this.form.username = res.data.data.username;
            this.form.nickname = res.data.data.nickname;
            this.form.phone = res.data.data.phone;
            this.form.address = res.data.data.address;
            this.form.password = res.data.data.password;
            this.form.description = res.data.data.description;
          } else {
            this.$message({
              message: "网络错误！",
              type: "error",
              duration: 1000,
              offset: 85,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
  },
  components: { SearchBar },
};
</script>

<style lang="scss">
.blog-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #34373c;
  padding-bottom: calc(20vh - 18px);

  .background-card {
    width: 85vw;
    height: 350px;
    margin: 10px;
    margin-top: 90px;
    display: flex;
    position: relative;

    img {
      width: 100%;
      display: block;
      border-radius: 10px;
    }

    .avatar {
      bottom: 15px;
      display: flex;
      margin-left: 15px;
      flex-direction: column-reverse;
      position: absolute;
    }

    .text-container {
      display: flex;
      flex-direction: column-reverse;
      padding-bottom: 110px;
      margin-left: 20px;
      position: absolute;
      bottom: -80px;
      left: 165px;
    }
  }

  .main-blog {
    margin-top: 10px;
    margin-bottom: 20px;
    width: 85vw;

    .el-tabs {
      border-radius: 10px;
    }
    .el-tabs--border-card > .el-tabs__header {
      border-top-right-radius: 10px;
      border-top-left-radius: 10px;
    }
    .el-tabs__nav-scroll {
      border-top-left-radius: 10px;
    }
  }

  /* 个人主页上传头像样式 */
  .avatar-uploader {
    display: flex;
    justify-content: space-between;
  }

  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .show_avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .change_avator {
    display: flex;
  }

  .change_avator p {
    font-family: "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",
      "微软雅黑", Arial, sans-serif;
    margin-left: 20px;
    margin-right: 22px;
  }

  .text-container > p {
    color: #fff;
    font-size: 50px;
  }

  /* 关注者卡片 */
  .follower_container {
    height: 100px;
  }

  .el-form {
    margin: 15px 10px;
  }

  .el-button {
    padding: 14px 40px;
    font-size: 18px;
    border-radius: 6px;
  }
}
</style>

